import { NextRequest } from 'next/server';
import { ResponseUtil } from '@/utils/response';
import { verifyAuth } from '@/utils/auth';
import { alipaySandboxConfig } from '@/config/alipay';
import crypto from 'crypto';
import prisma from '@/lib/prisma';

export async function POST(request: NextRequest) {
  try {
    // 验证用户登录
    const authResult = await verifyAuth(request);
    if (!authResult?.user?.id) {
      return ResponseUtil.unauthorized('未登录');
    }

    const { outBizNo } = await request.json();
    
    if (!outBizNo) {
      return ResponseUtil.badRequest('缺少转账单号');
    }

    // 检查配置
    if (!alipaySandboxConfig.appId || !alipaySandboxConfig.privateKey) {
      console.error('支付宝配置缺失:', {
        appId: !!alipaySandboxConfig.appId,
        privateKey: !!alipaySandboxConfig.privateKey
      });
      return ResponseUtil.serverError('支付宝配置不完整');
    }

    console.log('查询转账单号:', outBizNo);
    console.log('支付宝配置检查:', {
      appId: alipaySandboxConfig.appId,
      privateKeyLength: alipaySandboxConfig.privateKey.length
    });

    // 构建查询请求参数
    const queryParams: any = {
      app_id: alipaySandboxConfig.appId,
      method: 'alipay.fund.trans.common.query',
      charset: 'utf-8',
      sign_type: 'RSA2',
      timestamp: new Date().toISOString().replace('T', ' ').substring(0, 19),
      version: '1.0',
      biz_content: JSON.stringify({
        out_biz_no: outBizNo,
        product_code: 'TRANS_ACCOUNT_NO_PWD', // 添加必需的product_code参数
        biz_scene: 'DIRECT_TRANSFER' // 添加必需的biz_scene参数
      })
    };

    console.log('请求参数:', queryParams);
    console.log('biz_content:', queryParams.biz_content);

    // 生成签名
    const signString = Object.keys(queryParams)
      .filter(key => key !== 'sign')
      .sort()
      .map(key => `${key}=${queryParams[key]}`)
      .join('&');

    console.log('签名字符串:', signString);
    
    const privateKey = alipaySandboxConfig.privateKey;
    
    // 确保私钥格式正确
    let formattedPrivateKey = privateKey;
    if (!privateKey.includes('-----BEGIN RSA PRIVATE KEY-----')) {
      formattedPrivateKey = `-----BEGIN RSA PRIVATE KEY-----\n${privateKey}\n-----END RSA PRIVATE KEY-----`;
    }
    
    const sign = crypto.createSign('RSA-SHA256');
    sign.update(signString, 'utf8');
    const signature = sign.sign(formattedPrivateKey, 'base64');
    
    queryParams.sign = signature;
    console.log('生成的签名:', signature);

    // 发送查询请求到支付宝
    const response = await fetch(alipaySandboxConfig.gateway, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      },
      body: new URLSearchParams(queryParams)
    });

    const result = await response.text();
    console.log('支付宝转账查询响应:', result);

    // 解析支付宝响应
    let alipayResponse: any;
    
    try {
      // 检查响应是否为HTML（通常是错误页面）
      if (result.includes('<!DOCTYPE HTML') || result.includes('<html>')) {
        console.error('支付宝返回HTML错误页面:', result);
        
        // 尝试从HTML中提取错误信息
        if (result.includes('504 Gateway Time-out')) {
          return ResponseUtil.badRequest('支付宝网关超时，请稍后重试');
        } else if (result.includes('502 Bad Gateway')) {
          return ResponseUtil.badRequest('支付宝网关错误，请稍后重试');
        } else if (result.includes('500 Internal Server Error')) {
          return ResponseUtil.badRequest('支付宝服务器内部错误，请稍后重试');
        } else {
          return ResponseUtil.badRequest('支付宝服务暂时不可用，请稍后重试');
        }
      }
      
      // 尝试解析为URLSearchParams格式
      if (result.includes('alipay_fund_trans_common_query_response=')) {
        const responseParams = new URLSearchParams(result);
        let responseData = null;
        
        // 查找包含响应数据的参数
        for (const [key, value] of responseParams.entries()) {
          if (key.includes('alipay_fund_trans_common_query_response')) {
            try {
              responseData = JSON.parse(decodeURIComponent(value));
              break;
            } catch (parseError) {
              console.error('解析URL编码的响应数据失败:', parseError);
            }
          }
        }
        
        if (responseData) {
          alipayResponse = { alipay_fund_trans_common_query_response: responseData };
        }
      }
      
      // 如果上面没有解析成功，尝试直接JSON解析
      if (!alipayResponse) {
        try {
          alipayResponse = JSON.parse(result);
        } catch (jsonError) {
          console.error('JSON解析失败:', jsonError);
          console.error('原始响应内容:', result);
          return ResponseUtil.badRequest('支付宝响应格式错误，无法解析');
        }
      }
      
      console.log('支付宝响应详情:', alipayResponse);
      
      // 检查是否有错误响应
      if (alipayResponse.alipay_fund_trans_common_query_response) {
        const responseData = alipayResponse.alipay_fund_trans_common_query_response;

        if (responseData.code !== '10000') {
          const errorMsg = responseData.sub_msg || responseData.msg || '未知错误';
          const errorCode = responseData.sub_code || responseData.code || '未知错误码';
          console.error('支付宝查询失败:', { code: errorCode, message: errorMsg, fullResponse: responseData });
          return ResponseUtil.badRequest(`查询失败: ${errorMsg} (错误码: ${errorCode})`);
        }
        
        // 成功响应，检查转账状态
        const transferInfo = {
          outBizNo: responseData.out_biz_no,
          status: responseData.status,
          transAmount: responseData.trans_amount,
          transDate: responseData.trans_date,
          failReason: responseData.fail_reason,
          transMemo: responseData.trans_memo,
          createDate: responseData.create_date
        };
        
        // 如果转账成功，更新数据库中的提现记录状态
        if (responseData.status === 'SUCCESS') {
          try {
            await prisma.userWithdrawRecord.updateMany({
              where: {
                withdrawNo: outBizNo
              },
              data: {
                status: 'SUCCESS',
                completedAt: new Date(),
                alipayResponse: responseData
              }
            });
            console.log(`提现记录 ${outBizNo} 状态已更新为SUCCESS`);
          } catch (dbError) {
            console.error('更新提现记录状态失败:', dbError);
            // 即使数据库更新失败，也不影响查询结果的返回
          }
        }
        
        return ResponseUtil.success(transferInfo);
      } else if (alipayResponse.code !== '10000') {
        // 直接错误响应
        const errorMsg = alipayResponse.msg || alipayResponse.message || alipayResponse.sub_msg || '未知错误';
        const errorCode = alipayResponse.code || alipayResponse.sub_code || '未知错误码';
        console.error('支付宝查询失败:', { code: errorCode, message: errorMsg, fullResponse: alipayResponse });
        return ResponseUtil.badRequest(`查询失败: ${errorMsg} (错误码: ${errorCode})`);
      } else {
        // 无法识别的响应格式
        console.error('无法识别的支付宝响应格式:', alipayResponse);
        return ResponseUtil.badRequest('支付宝响应格式异常，无法处理');
      }
      
    } catch (error) {
      console.error('处理支付宝响应时发生错误:', error);
      return ResponseUtil.badRequest('处理支付宝响应失败');
    }

  } catch (error) {
    console.error('查询转账状态失败:', error);
    return ResponseUtil.serverError('查询转账状态失败');
  }
} 